{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 【Python自然语言处理】读书笔记：第五章：分类和标注词汇\n",
    "本章原文：https://usyiyi.github.io/nlp-py-2e-zh/5.html"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "本章的目的是要回答下列问题：\n",
    "\n",
    "    1. 什么是词汇分类，在自然语言处理中它们是如何使用？\n",
    "    \n",
    "    2. 一个好的存储词汇和它们的分类的Python数据结构是什么？\n",
    "    \n",
    "    3. 我们如何自动标注文本中词汇的词类？\n",
    "\n",
    "一路上，我们将介绍NLP的一些基本技术，包括序列标注、N-gram模型、回退和评估。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 1 使用词性标注器"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[('And', 'CC'), ('now', 'RB'), ('for', 'IN'), ('something', 'NN'), ('completely', 'RB'), ('different', 'JJ')]\n"
     ]
    }
   ],
   "source": [
    "from  nltk import *\n",
    "import nltk\n",
    "text = word_tokenize(\"And now for something completely different\")\n",
    "print(nltk.pos_tag(text))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "text.similar()方法接收一个单词w，找出所有上下文w1w w2，然后找出所有出现在相同上下文中的词w'，即w1w'w2。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "man time day year car moment world house family child country boy\n",
      "state job place way war girl work word\n",
      "None \n",
      "\n",
      "made said done put had seen found given left heard was been brought\n",
      "set got that took in told felt\n",
      "None \n",
      "\n",
      "in on to of and for with from at by that into as up out down through\n",
      "is all about\n",
      "None \n",
      "\n",
      "a his this their its her an that our any all one these my in your no\n",
      "some other and\n",
      "None \n",
      "\n"
     ]
    }
   ],
   "source": [
    "text = nltk.Text(word.lower() for word in nltk.corpus.brown.words())\n",
    "print(text.similar(\"woman\"),\"\\n\")\n",
    "print(text.similar(\"bought\"),\"\\n\")\n",
    "print(text.similar(\"over\"),\"\\n\")\n",
    "print(text.similar(\"the\"),\"\\n\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 2 已经标注的语料库\n",
    "## 2.1 表示已经标注的词符\n",
    "按照NLTK的约定，一个已标注的词符使用一个由词符和标记组成的元组来表示。我们可以使用函数str2tuple()从表示一个已标注的词符的标准字符串创建一个这样的特殊元组："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "('gly', 'NN') \n",
      " gly\n"
     ]
    }
   ],
   "source": [
    "tagged_token = nltk.tag.str2tuple(\"gly/NN\")\n",
    "print(tagged_token,\"\\n\",tagged_token[0])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "我们可以直接从一个字符串构造一个已标注的词符的列表。第一步是对字符串分词以便能访问单独的单词/标记字符串，然后将每一个转换成一个元组（使用str2tuple()）。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[('The', 'AT'), ('grand', 'JJ'), ('jury', 'NN'), ('commented', 'VBD'), ('on', 'IN'), ('a', 'AT'), ('number', 'NN'), ('of', 'IN'), ('other', 'AP'), ('topics', 'NNS'), (',', ','), ('AMONG', 'IN'), ('them', 'PPO'), ('the', 'AT'), ('Atlanta', 'NP'), ('and', 'CC'), ('Fulton', 'NP-TL'), ('County', 'NN-TL'), ('purchasing', 'VBG'), ('departments', 'NNS'), ('which', 'WDT'), ('it', 'PPS'), ('said', 'VBD'), ('``', '``'), ('ARE', 'BER'), ('well', 'QL'), ('operated', 'VBN'), ('and', 'CC'), ('follow', 'VB'), ('generally', 'RB'), ('accepted', 'VBN'), ('practices', 'NNS'), ('which', 'WDT'), ('inure', 'VB'), ('to', 'IN'), ('the', 'AT'), ('best', 'JJT'), ('interest', 'NN'), ('of', 'IN'), ('both', 'ABX'), ('governments', 'NNS'), (\"''\", \"''\"), ('.', '.')]\n"
     ]
    }
   ],
   "source": [
    "sent = '''\n",
    "The/AT grand/JJ jury/NN commented/VBD on/IN a/AT number/NN of/IN\n",
    "other/AP topics/NNS ,/, AMONG/IN them/PPO the/AT Atlanta/NP and/CC\n",
    "Fulton/NP-tl County/NN-tl purchasing/VBG departments/NNS which/WDT it/PPS\n",
    "said/VBD ``/`` ARE/BER well/QL operated/VBN and/CC follow/VB generally/RB\n",
    "accepted/VBN practices/NNS which/WDT inure/VB to/IN the/AT best/JJT\n",
    "interest/NN of/IN both/ABX governments/NNS ''/'' ./.\n",
    "'''\n",
    "print([nltk.tag.str2tuple(t) for t in sent.split()])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2.2 读取已标注的语料库\n",
    "NLTK中包括的若干语料库已标注了词性。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[('The', 'AT'), ('Fulton', 'NP-TL'), ...]\n"
     ]
    }
   ],
   "source": [
    "print(nltk.corpus.brown.tagged_words())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2.3 通用词性标记集"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[('NOUN', 30654), ('VERB', 14399), ('ADP', 12355), ('.', 11928), ('DET', 11389), ('ADJ', 6706), ('ADV', 3349), ('CONJ', 2717), ('PRON', 2535), ('PRT', 2264), ('NUM', 2166), ('X', 92)]\n"
     ]
    },
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAZsAAAEeCAYAAABc5biTAAAABHNCSVQICAgIfAhkiAAAA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aFX7RWg03kOBtybazUJjDkFUH7I0wbArmwjUh54jxsSLaD9kaYJhVzaHqELPkaMTteeIMfHCOsIkBruyOUT1peeIMcb4yZKNMcaYwCXFugLGGGMSnyUbY4wxgbNkY0wAROTPIjJfROaIyCwR8W3qiUpiTRWR7KCOb4wfrDeaMT4TkeOAc4GBqrpXRNrgDeViTL1lVzbG+C8D2KKqewFUdYuqrhORv4jIdBGZJyJjxD2d6K5MHheRHBFZKCKDRORtEVkqIve5bbqJyCIRedVt85aINKkYWETOFJFvRWSGiLwpIs1c+YMissBdaT0Sxd+FMYAlG2OC8DHQWUSWiMgzIvITV/6Uqg5S1X54DyaeG7ZPkapmA//Em/r4erxxx64UkdZumyOAZ1T1KGAHcF14UHcFdSdwuhvOJQe4xe1/AdBXVfsD9wVwzsZUy5KNMT5zD/pmAaOAzcAbInIlcIqIfCcic/EmN+sbttu77udcvEEt17sro+VAZ7dutap+7ZZfAU6oEPpYoA/wtYjMAkYCXYHtwB7gBRH5Od7T98ZEld2zMSYAqlqKNzr3VJdcrgX6A9mqulpE/g9oFLbLXvezLGy5/H3532nFh+IqvhdgiqqOqFgfERmMN2L4hcANeMnOmKixKxtjfCYiR4hI+EyWA4DFbnmLu49yYQSH7uI6HwBcCvy3wvppwFAROdzVo6mI9HbxWqrqJOBmIDOC2MbUil3ZGOO/ZsCTIpKGN6xRLl6T2jZgHrABmB7BcRcD14vIWGAB8Gz4SlXd7JrrXheRhq74TmAnMNFNQiZ4g8gaE1U2XI0xdYCIdAPed50LjKlzrBnNGGNM4OzKxhhjTODsysYYY0zgLNkYY4wJnCUbY4wxgbNkY4wxJnCWbIwxxgTOko0xxpjA/X8p2cpRVkDnNAAAAABJRU5ErkJggg==\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "from nltk.corpus import brown\n",
    "brown_news_tagged = brown.tagged_words(categories = \"news\", tagset = \"universal\")\n",
    "tag_fd = nltk.FreqDist(tag for (word, tag) in brown_news_tagged)\n",
    "print(tag_fd.most_common())\n",
    "tag_fd.plot(cumulative = True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "**********************************************************************\n",
      "  Resource 'corpora/cess_cat' not found.  Please use the NLTK\n",
      "  Downloader to obtain the resource:  >>> nltk.download()\n",
      "  Searched in:\n",
      "    - '/home/kuo/nltk_data'\n",
      "    - '/usr/share/nltk_data'\n",
      "    - '/usr/local/share/nltk_data'\n",
      "    - '/usr/lib/nltk_data'\n",
      "    - '/usr/local/lib/nltk_data'\n",
      "**********************************************************************\n",
      "\n",
      "**********************************************************************\n",
      "  Resource 'corpora/alpino' not found.  Please use the NLTK\n",
      "  Downloader to obtain the resource:  >>> nltk.download()\n",
      "  Searched in:\n",
      "    - '/home/kuo/nltk_data'\n",
      "    - '/usr/share/nltk_data'\n",
      "    - '/usr/local/share/nltk_data'\n",
      "    - '/usr/lib/nltk_data'\n",
      "    - '/usr/local/lib/nltk_data'\n",
      "**********************************************************************\n",
      "\n",
      "**********************************************************************\n",
      "  Resource 'corpora/sinica_treebank' not found.  Please use the\n",
      "  NLTK Downloader to obtain the resource:  >>> nltk.download()\n",
      "  Searched in:\n",
      "    - '/home/kuo/nltk_data'\n",
      "    - '/usr/share/nltk_data'\n",
      "    - '/usr/local/share/nltk_data'\n",
      "    - '/usr/lib/nltk_data'\n",
      "    - '/usr/local/lib/nltk_data'\n",
      "**********************************************************************\n"
     ]
    }
   ],
   "source": [
    "nltk.app.concordance()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2.4 名词\n",
    "名词一般指的是人、地点、事情或概念，例如: woman, Scotland, book, intelligence。\n",
    "\n",
    "名词可能出现在限定词和形容词之后，可以是动词的主语或宾语，如2.2所示。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['NOUN', 'DET', 'ADJ', 'ADP', '.', 'VERB', 'CONJ', 'NUM', 'ADV', 'PRT', 'PRON', 'X']\n"
     ]
    }
   ],
   "source": [
    "word_tag_pairs = nltk.bigrams(brown_news_tagged)\n",
    "noun_preceders = [a[1] for (a,b) in word_tag_pairs if b[1] == \"NOUN\"]\n",
    "fdist = nltk.FreqDist(noun_preceders)\n",
    "print([tag for (tag, _) in fdist.most_common()])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "这证实了我们的断言，名词出现在限定词和形容词之后，包括数字形容词（数词，标注为NUM）。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2.5 动词\n",
    "动词是用来描述事件和行动的词，例如2.3中的fall, eat。在一个句子中，动词通常表示涉及一个或多个名词短语所指示物的关系。\n",
    "\n",
    "一些动词的句法模式"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['is', 'said', 'was', 'are', 'be', 'has', 'have', 'will', 'says', 'would']\n"
     ]
    }
   ],
   "source": [
    "wsj = nltk.corpus.treebank.tagged_words(tagset = \"universal\")\n",
    "word_tag_fd = nltk.FreqDist(wsj)\n",
    "print([wt[0] for (wt, _) in word_tag_fd.most_common() if wt[1] == \"VERB\"][:10])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "请注意，频率分布中计算的项目是词-标记对。由于词汇和标记是成对的，我们可以把词作作为条件，标记作为事件，使用条件-事件对的链表初始化一个条件频率分布。这让我们看到了一个给定的词的标记的频率顺序列表："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[('VERB', 28), ('NOUN', 20)]\n",
      "[('VERB', 25), ('NOUN', 3)]\n"
     ]
    }
   ],
   "source": [
    "cfd1 = nltk.ConditionalFreqDist(wsj)\n",
    "print(cfd1[\"yield\"].most_common())\n",
    "print(cfd1[\"cut\"].most_common())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "我们可以颠倒配对的顺序，这样标记作为条件，词汇作为事件。现在我们可以看到对于一个给定的标记可能的词。我们将用《华尔街日报 》的标记集而不是通用的标记集来这样做："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['named', 'used', 'caused', 'exposed', 'reported', 'replaced', 'sold', 'died', 'expected', 'diagnosed']\n"
     ]
    }
   ],
   "source": [
    "wsj = nltk.corpus.treebank.tagged_words()\n",
    "cfd2 = nltk.ConditionalFreqDist((tag, word) for (word, tag) in wsj)\n",
    "print(list(cfd2[\"VBN\"])[:10])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "要弄清VBD（过去式）和VBN（过去分词）之间的区别，让我们找到可以同是VBD和VBN的词汇，看看一些它们周围的文字："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['used', 'even', 'brief', 'total', 'open', 'top', 'yielding', 'resigned', 'complete', 'like', 'free', 'last', 'related', 'troubled', 'complicated', 'underlying', 'record', 'working', 'close', 'direct', 'own', 'favored', 'accelerated', 'growing', 'combined', 'slow', 'elaborate', 'preferred', 'excise', 'tender', 'sweeping', 'single', 'capped', 'head', 'mature', 'clear', 'leading', 'suspect', 'engaging', 'back', 'planned', 'double', 'sound', 'beaten', 'needed', 'confused', 'mean', 'devastating', 'following', 'forcing', 'known', 'parallel', 'integrated', 'alleged', 'winning', 'split', 'interested', 'correct', 'advanced', 'funded', 'controlled', 'damaged', 'detailed', 'organized', 'laughing', 'limited', 'extended', 'disappointed', 'scared', 'heated', 'impending', 'live', 'diversified', 'upset', 'closing', 'midsized', 'present', 'qualified']\n"
     ]
    }
   ],
   "source": [
    "print([w for w in cfd1.conditions() if \"VERB\" in cfd1[w] and \"ADJ\" in cfd1[w]])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[('While', 'IN'), ('program', 'NN'), ('trades', 'NNS'), ('swiftly', 'RB'), ('kicked', 'VBD')]\n",
      "[('head', 'NN'), ('of', 'IN'), ('state', 'NN'), ('has', 'VBZ'), ('kicked', 'VBN')]\n"
     ]
    }
   ],
   "source": [
    "idx1 = wsj.index(('kicked', 'VBD'))\n",
    "print(wsj[idx1 - 4 : idx1 + 1])\n",
    "idx2 = wsj.index((\"kicked\", \"VBN\"))\n",
    "print(wsj[idx2 - 4 : idx2 + 1])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "在这种情况下，我们可以看到过去分词kicked前面是助动词have的形式。这是普遍真实的吗？"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2.6 形容词和副词\n",
    "另外两个重要的词类是形容词和副词。形容词修饰名词，可以作为修饰语（如the large pizza中的large），或者谓语（如the pizza is large）。英语形容词可以有内部结构（如the falling stocks中的fall+ing）。副词修饰动词，指定动词描述的事件的时间、方式、地点或方向（如the stocks fell quickly中的quickly）。副词也可以修饰的形容词（如Mary's teacher was really nice中的really）。\n",
    "\n",
    "英语中还有几个封闭的词类，如介词，冠词（也常称为限定词）（如the、a），情态动词（如should、may）和人称代词（如she、they）。每个词典和语法对这些词的分类都不同。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2.7 未简化的标记\n",
    "让我们找出每个名词类型中最频繁的名词。\n",
    "\n",
    "2.2中的程序找出所有以NN开始的标记，并为每个标记提供了几个示例单词。你会看到有许多NN的变种；最重要有$表示所有格名词，S表示复数名词（因为复数名词通常以s结尾），以及P表示专有名词。此外，大多数的标记都有后缀修饰符：-NC表示引用，-HL表示标题中的词，-TL表示标题（布朗标记的特征）。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "NN [('year', 137), ('time', 97), ('state', 88), ('week', 85), ('man', 72)]\n",
      "NN$ [(\"year's\", 13), (\"world's\", 8), (\"state's\", 7), (\"nation's\", 6), (\"city's\", 6)]\n",
      "NN$-HL [(\"Golf's\", 1), (\"Navy's\", 1)]\n",
      "NN$-TL [(\"President's\", 11), (\"Administration's\", 3), (\"Army's\", 3), (\"League's\", 3), (\"University's\", 3)]\n",
      "NN-HL [('sp.', 2), ('problem', 2), ('Question', 2), ('cut', 2), ('party', 2)]\n",
      "NN-NC [('ova', 1), ('eva', 1), ('aya', 1)]\n",
      "NN-TL [('President', 88), ('House', 68), ('State', 59), ('University', 42), ('City', 41)]\n",
      "NN-TL-HL [('Fort', 2), ('Mayor', 1), ('Commissioner', 1), ('City', 1), ('Oak', 1)]\n",
      "NNS [('years', 101), ('members', 69), ('people', 52), ('sales', 51), ('men', 46)]\n",
      "NNS$ [(\"children's\", 7), (\"women's\", 5), (\"men's\", 3), (\"janitors'\", 3), (\"taxpayers'\", 2)]\n",
      "NNS$-HL [(\"Dealers'\", 1), (\"Idols'\", 1)]\n",
      "NNS$-TL [(\"Women's\", 4), (\"States'\", 3), (\"Giants'\", 2), (\"Princes'\", 1), (\"Bombers'\", 1)]\n",
      "NNS-HL [('Wards', 1), ('deputies', 1), ('bonds', 1), ('aspects', 1), ('Decisions', 1)]\n",
      "NNS-TL [('States', 38), ('Nations', 11), ('Masters', 10), ('Communists', 9), ('Rules', 9)]\n",
      "NNS-TL-HL [('Nations', 1)]\n"
     ]
    }
   ],
   "source": [
    "def findtags(tag_prefix, tagged_text):\n",
    "    cfd = nltk.ConditionalFreqDist((tag, word) for (word, tag) in tagged_text if tag.startswith(tag_prefix))\n",
    "    return dict((tag, cfd[tag].most_common(5)) for tag in cfd.conditions())\n",
    "\n",
    "tagdict = findtags(\"NN\", nltk.corpus.brown.tagged_words(categories = \"news\"))\n",
    "for tag in sorted(tagdict):\n",
    "    print(tag, tagdict[tag])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2.8 探索已标注的语料库\n",
    "让我们简要地回过来探索语料库，我们在前面的章节中看到过，这次我们探索词性标记。\n",
    "\n",
    "假设我们正在研究词often，想看看它是如何在文本中使用的。我们可以试着看看跟在often后面的词汇"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[',', '.', 'accomplished', 'analytically', 'appear', 'apt', 'associated', 'assuming', 'became', 'become', 'been', 'began', 'call', 'called', 'carefully', 'chose', 'classified', 'colorful', 'composed', 'contain', 'differed', 'difficult', 'encountered', 'enough', 'equate', 'extremely', 'found', 'happens', 'have', 'ignored', 'in', 'involved', 'more', 'needed', 'nightly', 'observed', 'of', 'on', 'out', 'quite', 'represent', 'responsible', 'revamped', 'seclude', 'set', 'shortened', 'sing', 'sounded', 'stated', 'still', 'sung', 'supported', 'than', 'to', 'when', 'work']\n"
     ]
    }
   ],
   "source": [
    "brown_learned_text = brown.words(categories = \"learned\")\n",
    "print(sorted(set(b for (a, b) in nltk.bigrams(brown_learned_text) if a == \"often\")))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "然而，使用tagged_words()方法查看跟随词的词性标记可能更有指导性："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "VERB  ADV  ADP  ADJ    .  PRT \n",
      "  37    8    7    6    4    2 \n"
     ]
    }
   ],
   "source": [
    "brown_lrnd_tagged = brown.tagged_words(categories = \"learned\", tagset = \"universal\")\n",
    "tags = [b[1] for (a, b) in nltk.bigrams(brown_lrnd_tagged) if a[0] == \"often\"]\n",
    "fd = nltk.FreqDist(tags)\n",
    "fd.tabulate()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "请注意often后面最高频率的词性是动词。名词从来没有在这个位置出现（在这个特别的语料中）。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "接下来，让我们看一些较大范围的上下文，找出涉及特定标记和词序列的词（在这种情况下，\"Verb to Verb\"）。在code-three-word-phrase中，我们考虑句子中的每个三词窗口[1]，检查它们是否符合我们的标准[2]。如果标记匹配，我们输出对应的词[3]。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "combined to achieve\n",
      "continue to place\n",
      "serve to protect\n",
      "wanted to wait\n",
      "allowed to place\n",
      "expected to become\n",
      "expected to approve\n",
      "expected to make\n",
      "intends to make\n",
      "seek to set\n",
      "like to see\n"
     ]
    }
   ],
   "source": [
    "from nltk.corpus import brown\n",
    "def process(sentence):\n",
    "    for (w1, t1), (w2, t2), (w3, t3) in nltk.trigrams(sentence):\n",
    "        if (t1.startswith(\"V\") and t2 == \"TO\" and t3.startswith(\"V\")):\n",
    "            print(w1, w2, w3)\n",
    "count = 0\n",
    "for tagged_sent in brown.tagged_sents():\n",
    "    process(tagged_sent)\n",
    "    count += 1\n",
    "    if count >= 100:\n",
    "        break\n",
    "    "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "最后，让我们看看与它们的标记关系高度模糊不清的词。了解为什么要标注这样的词是因为它们各自的上下文可以帮助我们弄清楚标记之间的区别。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "best ADJ ADV VERB NOUN\n",
      "close ADV ADJ VERB NOUN\n",
      "open ADJ VERB NOUN ADV\n",
      "present ADJ ADV NOUN VERB\n",
      "that ADP DET PRON ADV\n"
     ]
    }
   ],
   "source": [
    "brown_news_tagged = brown.tagged_words(categories = \"news\", tagset = \"universal\")\n",
    "data = nltk.ConditionalFreqDist((word.lower(), tag) for (word, tag) in brown_news_tagged)\n",
    "for word in sorted(data.conditions()):\n",
    "    if len(data[word]) > 3:\n",
    "        tags = [tag for (tag, _) in data[word].most_common()]\n",
    "        print(word, \" \".join(tags))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 3 使用Python字典映射单词到其属性"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3.3 定义字典\n",
    "我们可以使用键-值对格式创建字典。有两种方式做这个，我们通常会使用第一个："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 55,
   "metadata": {},
   "outputs": [],
   "source": [
    "pos = {\"colorless\": \"ADJ\", \"ideas\": \"N\", \"sleep\": \"V\", \"furiously\": \"ADV\"}\n",
    "pos = dict(colorless = \"ADJ\", ideas = \"N\", sleep = \"V\", furiously = \"ADV\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "请注意，字典的键必须是不可改变的类型，如字符串和元组。如果我们尝试使用可变键定义字典会得到一个TypeError："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 56,
   "metadata": {},
   "outputs": [
    {
     "ename": "TypeError",
     "evalue": "unhashable type: 'list'",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mTypeError\u001b[0m                                 Traceback (most recent call last)",
      "\u001b[0;32m<ipython-input-56-2ef56052ab4d>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mpos\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m{\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m\"ideas\"\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m\"blogs\"\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m\"adventures\"\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m:\u001b[0m \u001b[0;34m\"N\"\u001b[0m\u001b[0;34m}\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[0;31mTypeError\u001b[0m: unhashable type: 'list'"
     ]
    }
   ],
   "source": [
    "pos = {[\"ideas\", \"blogs\", \"adventures\"]: \"N\"}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3.4 默认字典\n",
    "\n",
    "如果我们试图访问一个不在字典中的键，会得到一个错误。然而，如果一个字典能为这个新键自动创建一个条目并给它一个默认值，如0或者一个空链表，将是有用的。由于这个原因，可以使用一种特殊的称为defaultdict的字典。为了使用它，我们必须提供一个参数，用来创建默认值，如int, float, str, list, dict, tuple。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 58,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "4\n",
      "0\n",
      "[]\n"
     ]
    }
   ],
   "source": [
    "from collections import defaultdict\n",
    "frequency = defaultdict(int)\n",
    "frequency[\"colorless\"] = 4\n",
    "print(frequency[\"colorless\"])\n",
    "print(frequency[\"new\"])\n",
    "pos = defaultdict(list)\n",
    "pos[\"sleep\"] = [\"NOUN\", \"VERB\"]\n",
    "print(pos[\"new\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "这些默认值实际上是将其他对象转换为指定类型的函数（例如int(\"2\"), list(\"2\")）。当它们不带参数被调用时——int(), list()——它们分别返回0和[] 。\n",
    "\n",
    "前面的例子中指定字典项的默认值为一个特定的数据类型的默认值。然而，也可以指定任何我们喜欢的默认值，只要提供可以无参数的被调用产生所需值的函数的名子。让我们回到我们的词性的例子，创建一个任一条目的默认值是'N'的字典[1]。当我们访问一个不存在的条目时[2]，它会自动添加到字典[3]。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 59,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "NOUN\n",
      "[defaultdict(<function <lambda> at 0x7fa3e3cb51e0>, {'colorless': 'ADJ', 'blog': 'NOUN'})]\n"
     ]
    }
   ],
   "source": [
    "pos = defaultdict(lambda: \"NOUN\")\n",
    "pos[\"colorless\"] = \"ADJ\"\n",
    "print(pos[\"blog\"])\n",
    "print([pos])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "让我们来看看默认字典如何被应用在较大规模的语言处理任务中。许多语言处理任务——包括标注——费很大力气来正确处理文本中只出现过一次的词。如果有一个固定的词汇和没有新词会出现的保证，它们会有更好的表现。在一个默认字典的帮助下，我们可以预处理一个文本，替换低频词汇为一个特殊的“超出词汇表”词符UNK。（你能不看下面的想出如何做吗？）\n",
    "\n",
    "我们需要创建一个默认字典，映射每个词为它们的替换词。最频繁的n个词将被映射到它们自己。其他的被映射到UNK。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 61,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['[', 'Alice', \"'\", 's', 'Adventures', 'in', 'Wonderland', 'by', 'UNK', 'UNK']\n",
      "34110\n",
      "34110\n"
     ]
    }
   ],
   "source": [
    "alice = nltk.corpus.gutenberg.words(\"carroll-alice.txt\")\n",
    "vocab = nltk.FreqDist(alice)\n",
    "v1000 = [word for (word, _) in vocab.most_common(1000)]\n",
    "mapping = defaultdict(lambda: \"UNK\")\n",
    "for v in v1000:\n",
    "    mapping[v] = v\n",
    "alice2 = [mapping[v] for v in alice]\n",
    "print(alice2[:10])\n",
    "print(len(alice))\n",
    "print(len(alice2))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 3.5 递增地更新字典\n",
    "我们可以使用字典计数出现的次数，模拟fig-tally所示的计数词汇的方法。首先初始化一个空的defaultdict，然后处理文本中每个词性标记。如果标记以前没有见过，就默认计数为零。每次我们遇到一个标记，就使用+=运算符递增它的计数。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 62,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "30654\n",
      "['.', 'ADJ', 'ADP', 'ADV', 'CONJ', 'DET', 'NOUN', 'NUM', 'PRON', 'PRT', 'VERB', 'X']\n"
     ]
    }
   ],
   "source": [
    "from collections import defaultdict\n",
    "counts = defaultdict(int)\n",
    "from nltk.corpus import brown\n",
    "for (word, tag) in brown.tagged_words(categories = \"news\", tagset = \"universal\"):\n",
    "    counts[tag] += 1\n",
    "print(counts[\"NOUN\"])\n",
    "print(sorted(counts))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 63,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[('NOUN', 30654), ('VERB', 14399), ('ADP', 12355), ('.', 11928), ('DET', 11389), ('ADJ', 6706), ('ADV', 3349), ('CONJ', 2717), ('PRON', 2535), ('PRT', 2264), ('NUM', 2166), ('X', 92)]\n",
      "['NOUN', 'VERB', 'ADP', '.', 'DET', 'ADJ', 'ADV', 'CONJ', 'PRON', 'PRT', 'NUM', 'X']\n"
     ]
    }
   ],
   "source": [
    "from operator import itemgetter\n",
    "print(sorted(counts.items(), key = itemgetter(1), reverse = True))\n",
    "print([t for t, c in sorted(counts.items(), key = itemgetter(1), reverse = True)])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "列表演示了一个重要的按值排序一个字典的习惯用法，来按频率递减顺序显示词汇。sorted()的第一个参数是要排序的项目，它是由一个词性标记和一个频率组成的元组的列表。第二个参数使用函数itemgetter()指定排序的键。在一般情况下，itemgetter(n)返回一个函数，这个函数可以在一些其他序列对象上被调用获得这个序列的第n个元素，例如："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 64,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "8336\n",
      "8336\n"
     ]
    }
   ],
   "source": [
    "pair = (\"NP\", 8336)\n",
    "print(pair[1])\n",
    "print(itemgetter(1)(pair))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "sorted()的最后一个参数指定项目是否应被按相反的顺序返回，即频率值递减。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "在3.3的开头还有第二个有用的习惯用法，那里我们初始化一个defaultdict，然后使用for循环来更新其值。下面是一个示意版本：\n",
    "```py\n",
    ">>> my_dictionary = defaultdict(function to create default value)\n",
    "\n",
    ">>> for item in sequence:\n",
    "... my_dictionary[item_key] is updated with information about item\n",
    "```\n",
    "下面是这种模式的另一个示例，我们按它们最后两个字母索引词汇："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 67,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['abactinally', 'abandonedly', 'abasedly', 'abashedly', 'abashlessly', 'abbreviately', 'abdominally', 'abhorrently', 'abidingly', 'abiogenetically']\n",
      "['blazy', 'bleezy', 'blowzy', 'boozy', 'breezy', 'bronzy', 'buzzy', 'Chazy', 'cozy', 'crazy']\n"
     ]
    }
   ],
   "source": [
    "last_letters = defaultdict(list)\n",
    "words = nltk.corpus.words.words(\"en\")\n",
    "for word in words:\n",
    "    key = word[-2:]\n",
    "    last_letters[key].append(word)\n",
    "print(last_letters[\"ly\"][:10])\n",
    "print(last_letters[\"zy\"][:10])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "下面的例子使用相同的模式创建一个颠倒顺序的词字典。（你可能会试验第3行来弄清楚为什么这个程序能运行。）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 73,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['entrail', 'latrine', 'ratline', 'reliant', 'retinal', 'trenail']\n"
     ]
    }
   ],
   "source": [
    "anagrams = defaultdict(list)\n",
    "for word in words:\n",
    "    key = \"\".join(sorted(word))\n",
    "    anagrams[key].append(word)\n",
    "print(anagrams[\"aeilnrt\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "由于积累这样的词是如此常用的任务，NLTK提供一个创建defaultdict(list)更方便的方式，形式为nltk.Index()。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 75,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['entrail', 'latrine', 'ratline', 'reliant', 'retinal', 'trenail']\n"
     ]
    }
   ],
   "source": [
    "anagrams = nltk.Index((''.join(sorted(w)), w) for w in words)\n",
    "print(anagrams[\"aeilnrt\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "nltk.Index是一个支持额外初始化的defaultdict(list)。类似地，nltk.FreqDist本质上是一个额外支持初始化的defaultdict(int)（附带排序和绘图方法）。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3.6 复杂的键和值\n",
    "我们可以使用具有复杂的键和值的默认字典。让我们研究一个词可能的标记的范围，给定词本身和它前一个词的标记。我们将看到这些信息如何被一个词性标注器使用。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 77,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "defaultdict(<class 'int'>, {'NOUN': 5, 'ADJ': 11})\n"
     ]
    }
   ],
   "source": [
    "pos = defaultdict(lambda: defaultdict(int))\n",
    "brown_news_tagged = brown.tagged_words(categories = \"news\", tagset = \"universal\")\n",
    "for ((w1, t1), (w2, t2)) in nltk.bigrams(brown_news_tagged):\n",
    "    pos[(t1, w2)][t2] += 1\n",
    "print(pos[(\"DET\", \"right\")])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "这个例子使用一个字典，它的条目的默认值也是一个字典（其默认值是int()，即0）。请注意我们如何遍历已标注语料库的双连词，每次遍历处理一个词-标记对[1]。每次通过循环时，我们更新字典pos中的条目(t1, w2)，一个标记和它后面的词[2]。当我们在pos中查找一个项目时，我们必须指定一个复合键[3]，然后得到一个字典对象。一个词性标注器可以使用这些信息来决定词right，前面是一个限定词时，应标注为ADJ。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3.7 反转字典\n",
    "字典支持高效查找，只要你想获得任意键的值。如果d是一个字典，k是一个键，输入d[k]，就立即获得值。给定一个值查找对应的键要慢一些和麻烦一些："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 79,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['mortal', 'Against', 'Him', 'There', 'brought', 'King', 'virtue', 'every', 'been', 'thine']\n"
     ]
    }
   ],
   "source": [
    "counts = defaultdict(int)\n",
    "for word in nltk.corpus.gutenberg.words(\"milton-paradise.txt\"):\n",
    "    counts[word] +=1\n",
    "print([key for (key, value) in counts.items() if value == 32])\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "如果我们希望经常做这样的一种“反向查找”，建立一个映射值到键的字典是有用的。在没有两个键具有相同的值情况，这是一个容易的事。只要得到字典中的所有键-值对，并创建一个新的值-键对字典。下一个例子演示了用键-值对初始化字典pos的另一种方式。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 80,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "ideas\n"
     ]
    }
   ],
   "source": [
    "pos = {\"colorless\": \"ADj\", \"ideas\": \"N\", \"sleep\": \"V\", \"furiously\": \"ADV\"}\n",
    "pos2 = dict((value, key) for (key, value) in pos.items())\n",
    "print(pos2[\"N\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "首先让我们将我们的词性字典做的更实用些，使用字典的update()方法加入再一些词到pos中，创建多个键具有相同的值的情况。这样一来，刚才看到的反向查找技术就将不再起作用（为什么不？）作为替代，我们不得不使用append()积累词和每个词性，如下所示："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 82,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['ideas', 'cats']\n"
     ]
    }
   ],
   "source": [
    "pos.update({'cats': 'N', 'scratch': 'V', 'peacefully': 'ADV', 'old': 'ADJ'})\n",
    "pos2 = defaultdict(list)\n",
    "for key, value in pos.items():\n",
    "    pos2[value].append(key)\n",
    "print(pos2[\"N\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "现在，我们已经反转字典pos，可以查任意词性找到所有具有此词性的词。可以使用NLTK中的索引支持更容易的做同样的事，如下所示："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 83,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['furiously', 'peacefully']\n"
     ]
    }
   ],
   "source": [
    "pos2 = nltk.Index((value, key) for (key, value) in pos.items())\n",
    "print(pos2[\"ADV\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4.1 默认标注器\n",
    "最简单的标注器是为每个词符分配同样的标记。这似乎是一个相当平庸的一步，但它建立了标注器性能的一个重要的底线。为了得到最好的效果，我们用最有可能的标记标注每个词。让我们找出哪个标记是最有可能的（现在使用未简化标记集）："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 85,
   "metadata": {},
   "outputs": [],
   "source": [
    "from nltk.corpus import brown\n",
    "brown_tagged_sents = brown.tagged_sents(categories='news')\n",
    "brown_sents = brown.sents(categories='news')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 86,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "NN\n"
     ]
    }
   ],
   "source": [
    "tags = [tag for (word, tag) in brown.tagged_words(categories = \"news\")]\n",
    "print(nltk.FreqDist(tags).max())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "现在我们可以创建一个将所有词都标注成NN的标注器。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 87,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[('I', 'NN'), ('do', 'NN'), ('not', 'NN'), ('like', 'NN'), ('green', 'NN'), ('eggs', 'NN'), ('and', 'NN'), ('ham', 'NN'), (',', 'NN'), ('I', 'NN')]\n"
     ]
    }
   ],
   "source": [
    "raw = \"I do not like green eggs and ham, I do not like them Sam I am!\"\n",
    "tokens = word_tokenize(raw)\n",
    "default_tagger = nltk.DefaultTagger(\"NN\")\n",
    "print(default_tagger.tag(tokens)[:10])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "不出所料，这种方法的表现相当不好。在一个典型的语料库中，它只标注正确了八分之一的标识符，正如我们在这里看到的："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 88,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.13089484257215028"
      ]
     },
     "execution_count": 88,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "default_tagger.evaluate(brown_tagged_sents)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "默认的标注器给每一个单独的词分配标记，即使是之前从未遇到过的词。碰巧的是，一旦我们处理了几千词的英文文本之后，大多数新词都将是名词。正如我们将看到的，这意味着，默认标注器可以帮助我们提高语言处理系统的稳定性。我们将很快回来讲述这个。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4.2 正则表达式标注器\n",
    "\n",
    "正则表达式标注器基于匹配模式分配标记给词符。例如，我们可能会猜测任一以ed结尾的词都是动词过去分词，任一以's结尾的词都是名词所有格。可以用一个正则表达式的列表表示这些："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 89,
   "metadata": {},
   "outputs": [],
   "source": [
    ">>> patterns = [\n",
    "...     (r'.*ing$', 'VBG'),               # gerunds\n",
    "...     (r'.*ed$', 'VBD'),                # simple past\n",
    "...     (r'.*es$', 'VBZ'),                # 3rd singular present\n",
    "...     (r'.*ould$', 'MD'),               # modals\n",
    "...     (r'.*\\'s$', 'NN$'),               # possessive nouns\n",
    "...     (r'.*s$', 'NNS'),                 # plural nouns\n",
    "...     (r'^-?[0-9]+(.[0-9]+)?$', 'CD'),  # cardinal numbers\n",
    "...     (r'.*', 'NN')                     # nouns (default)\n",
    "... ]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "请注意，这些是顺序处理的，第一个匹配上的会被使用。现在我们可以建立一个标注器，并用它来标记一个句子。做完这一步会有约五分之一是正确的。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 93,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[('``', 'NN'), ('Only', 'NN'), ('a', 'NN'), ('relative', 'NN'), ('handful', 'NN'), ('of', 'NN'), ('such', 'NN'), ('reports', 'NNS'), ('was', 'NNS'), ('received', 'VBD'), (\"''\", 'NN'), (',', 'NN'), ('the', 'NN'), ('jury', 'NN'), ('said', 'NN'), (',', 'NN'), ('``', 'NN'), ('considering', 'VBG'), ('the', 'NN'), ('widespread', 'NN'), ('interest', 'NN'), ('in', 'NN'), ('the', 'NN'), ('election', 'NN'), (',', 'NN'), ('the', 'NN'), ('number', 'NN'), ('of', 'NN'), ('voters', 'NNS'), ('and', 'NN'), ('the', 'NN'), ('size', 'NN'), ('of', 'NN'), ('this', 'NNS'), ('city', 'NN'), (\"''\", 'NN'), ('.', 'NN')]\n",
      "0.20326391789486245\n"
     ]
    }
   ],
   "source": [
    "regexp_tagger = nltk.RegexpTagger(patterns)\n",
    "print(regexp_tagger.tag(brown_sents[3]))\n",
    "print(regexp_tagger.evaluate(brown_tagged_sents))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "最终的正则表达式«.*»是一个全面捕捉的，标注所有词为名词。这与默认标注器是等效的（只是效率低得多）。除了作为正则表达式标注器的一部分重新指定这个，有没有办法结合这个标注器和默认标注器呢？我们将很快看到如何做到这一点。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4.3 查询标注器\n",
    "很多高频词没有NN标记。让我们找出100个最频繁的词，存储它们最有可能的标记。然后我们可以使用这个信息作为“查找标注器”（NLTK UnigramTagger）的模型："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 100,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['AT']\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "0.45578495136941344"
      ]
     },
     "execution_count": 100,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "fd = nltk.FreqDist(brown.words(categories = \"news\"))\n",
    "cfd = nltk.ConditionalFreqDist(brown.tagged_words(categories = \"news\"))\n",
    "most_freq_words = fd.most_common(100)\n",
    "likely_tags = dict((word, cfd[word].max()) for (word, _) in most_freq_words)\n",
    "print([cfd[\"the\"].max()])\n",
    "baseline_tagger = nltk.UnigramTagger(model = likely_tags)\n",
    "baseline_tagger.evaluate(brown_tagged_sents)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "现在应该并不奇怪，仅仅知道100个最频繁的词的标记就使我们能正确标注很大一部分词符（近一半，事实上）。让我们来看看它在一些未标注的输入文本上做的如何："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 106,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[('``', '``'), ('Only', None), ('a', 'AT'), ('relative', None), ('handful', None), ('of', 'IN'), ('such', None), ('reports', None), ('was', 'BEDZ'), ('received', None), (\"''\", \"''\"), (',', ','), ('the', 'AT'), ('jury', None), ('said', 'VBD'), (',', ','), ('``', '``'), ('considering', None), ('the', 'AT'), ('widespread', None), ('interest', None), ('in', 'IN'), ('the', 'AT'), ('election', None), (',', ','), ('the', 'AT'), ('number', None), ('of', 'IN'), ('voters', None), ('and', 'CC'), ('the', 'AT'), ('size', None), ('of', 'IN'), ('this', 'DT'), ('city', None), (\"''\", \"''\"), ('.', '.')]\n"
     ]
    }
   ],
   "source": [
    "sent = brown.sents(categories='news')[3]\n",
    "print(baseline_tagger.tag(sent))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "许多词都被分配了一个None标签，因为它们不在100个最频繁的词之中。在这些情况下，我们想分配默认标记NN。换句话说，我们要先使用查找表，如果它不能指定一个标记就使用默认标注器，这个过程叫做回退（5）。我们可以做到这个，通过指定一个标注器作为另一个标注器的参数，如下所示。现在查找标注器将只存储名词以外的词的词-标记对，只要它不能给一个词分配标记，它将会调用默认标注器。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 107,
   "metadata": {},
   "outputs": [],
   "source": [
    "baseline_tagger = nltk.UnigramTagger(model = likely_tags, backoff = nltk.DefaultTagger(\"NN\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "让我们把所有这些放在一起，写一个程序来创建和评估具有一定范围的查找标注器 ，4.1。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 109,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAYUAAAEWCAYAAACJ0YulAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADl0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uIDMuMC4zLCBodHRwOi8vbWF0cGxvdGxpYi5vcmcvnQurowAAIABJREFUeJzt3Xu8VXWd//HXG8RLioECjQKCGmqkWXY0J7WLqZEpWHZRUTMzaky7WE0WZeYMjWU1j5rxl6Fjap5CMy2aTO2m1pQKXhFNRUSBvIAXvCAK8vn98f3ucxabvc/eB8461/fz8diPs9dlr/XZa6+zPuv7XWt9v4oIzMzMAAb1dABmZtZ7OCmYmVkbJwUzM2vjpGBmZm2cFMzMrI2TgpmZtXFS6ICk6yWd1NNxDBSSRkv6q6TnJM3o6Xj6AkkHSbqzg+m7SVrTnTF1hqQ/Sv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FKbMrcAt0j6HfBjUs9e7QuVds/j3pYTySBSO/xv3IhYzZrm6iMbaC4EvhER86rG/5lc/SPpHcDySP1b3Agck8e/h9StJaQG2T4gaVSeto2kcfVWKml7FfpOJrXP/3DVPMNI1zmOj4hlADmGhyR9MM8jSXt2+lubNcklBRtQImIJ8IMak84ELpR0F7CS9qaZvwH8TNJ84K/AI3k590j6KqkHukGkljU/RdWBvmAI8B1J2wOrgGXAJ6vmmULqM/r8SlVRLiFMBX6Y1zeEdG3kzs59c7PmuJVUMzNr4+ojMzNr46RgZmZtnBTMzKyNk4KZmbVxUjAzszZOCmZm1sZJwczM2vx/dInE9+2SxNsAAAAASUVORK5CYII=\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "def performance(cfd, wordlist):\n",
    "    lt = dict((word, cfd[word].max()) for word in wordlist)\n",
    "    baseline_tagger = nltk.UnigramTagger(model = lt, backoff = nltk.DefaultTagger(\"NN\"))\n",
    "    return baseline_tagger.evaluate(brown.tagged_sents(categories = \"news\"))\n",
    "\n",
    "def display():\n",
    "    import pylab\n",
    "    word_freqs = nltk.FreqDist(brown.words(categories = \"news\")).most_common()\n",
    "    words_by_freq = [w for (w, _) in word_freqs]\n",
    "    cfd = nltk.ConditionalFreqDist(brown.tagged_words(categories = \"news\"))\n",
    "    sizes = 2 ** pylab.arange(15)\n",
    "    perfs = [performance(cfd, words_by_freq[:size]) for size in sizes]\n",
    "    pylab.plot(sizes, perfs, \"-bo\")\n",
    "    pylab.title(\"Lookup Tagger Performancce with Varying Model Size\")\n",
    "    pylab.xlabel(\"Model Size\")\n",
    "    pylab.ylabel(\"Performance\")\n",
    "    pylab.show()\n",
    "display()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "可以观察到，随着模型规模的增长，最初的性能增加迅速，最终达到一个稳定水平，这时模型的规模大量增加性能的提高很小。（这个例子使用pylab绘图软件包，在4.8讨论过）。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4.4 评估\n",
    "在前面的例子中，你会注意到对准确性得分的强调。事实上，评估这些工具的表现是NLP的一个中心主题。回想fig-sds中的处理流程；一个模块输出中的任何错误都在下游模块大大的放大。\n",
    "\n",
    "我们对比人类专家分配的标记来评估一个标注器的表现。由于我们通常很难获得专业和公正的人的判断，所以使用黄金标准测试数据来代替。这是一个已经手动标注并作为自动系统评估标准而被接受的语料库。当标注器对给定词猜测的标记与黄金标准标记相同，标注器被视为是正确的。\n",
    "\n",
    "当然，设计和实施原始的黄金标准标注的也是人。更深入的分析可能会显示黄金标准中的错误，或者可能最终会导致一个修正的标记集和更复杂的指导方针。然而，黄金标准就目前有关的自动标注器的评估而言被定义成“正确的”。\n",
    "\n",
    "注意\n",
    "\n",
    "开发一个已标注语料库是一个重大的任务。除了数据，它会产生复杂的工具、文档和实践，为确保高品质的标注。标记集和其他编码方案不可避免地依赖于一些理论主张，不是所有的理论主张都被共享，然而，语料库的创作者往往竭尽全力使他们的工作尽可能理论中立，以最大限度地提高其工作的有效性。我们将在11.讨论创建一个语料库的挑战。\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 5 N-gram标注\n",
    "## 5.1 一元标注\n",
    "\n",
    "一元标注器基于一个简单的统计算法：对每个标识符分配这个独特的标识符最有可能的标记。例如，它将分配标记JJ给词frequent的所有出现，因为frequent用作一个形容词（例如a frequent word）比用作一个动词（例如I frequent this cafe）更常见。一个一元标注器的行为就像一个查找标注器（4），除了有一个更方便的建立它的技术，称为训练。在下面的代码例子中，我们训练一个一元标注器，用它来标注一个句子，然后评估："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 112,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[('Various', 'JJ'), ('of', 'IN'), ('the', 'AT'), ('apartments', 'NNS'), ('are', 'BER'), ('of', 'IN'), ('the', 'AT'), ('terrace', 'NN'), ('type', 'NN'), (',', ','), ('being', 'BEG'), ('on', 'IN'), ('the', 'AT'), ('ground', 'NN'), ('floor', 'NN'), ('so', 'QL'), ('that', 'CS'), ('entrance', 'NN'), ('is', 'BEZ'), ('direct', 'JJ'), ('.', '.')]\n",
      "0.9349006503968017\n"
     ]
    }
   ],
   "source": [
    "from nltk.corpus import brown\n",
    "brown_tagged_sents = brown.tagged_sents(categories = \"news\")\n",
    "brown_sents = brown.sents(categories = \"news\")\n",
    "unigram_tagger = nltk.UnigramTagger(brown_tagged_sents)\n",
    "print(unigram_tagger.tag(brown_sents[2007]))\n",
    "print(unigram_tagger.evaluate(brown_tagged_sents))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "我们训练一个UnigramTagger，通过在我们初始化标注器时指定已标注的句子数据作为参数。训练过程中涉及检查每个词的标记，将所有词的最可能的标记存储在一个字典里面，这个字典存储在标注器内部。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 5.2 分离训练和测试数据\n",
    "\n",
    "现在，我们正在一些数据上训练一个标注器，必须小心不要在相同的数据上测试，如我们在前面的例子中的那样。一个只是记忆它的训练数据，而不试图建立一个一般的模型的标注器会得到一个完美的得分，但在标注新的文本时将是无用的。相反，我们应该分割数据，90％为测试数据，其余10％为测试数据："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 113,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "4160\n",
      "0.8121200039868434\n"
     ]
    }
   ],
   "source": [
    "size = int(len(brown_tagged_sents) * 0.9)\n",
    "print(size)\n",
    "train_sents = brown_tagged_sents[:size]\n",
    "test_sents = brown_tagged_sents[size:]\n",
    "unigram_tagger = nltk.UnigramTagger(train_sents)\n",
    "print(unigram_tagger.evaluate(test_sents))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "虽然得分更糟糕了，但是现在我们对这种标注器的用处有了更好的了解，如它在之前没有遇见的文本上的表现。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 5.3 一般的N-gram标注\n",
    "\n",
    "在基于一元处理一个语言处理任务时，我们使用上下文中的一个项目。标注的时候，我们只考虑当前的词符，与更大的上下文隔离。给定一个模型，我们能做的最好的是为每个词标注其先验的最可能的标记。这意味着我们将使用相同的标记标注一个词，如wind，不论它出现的上下文是the wind还是to wind。\n",
    "\n",
    "一个n-gram tagger标注器是一个一元标注器的一般化，它的上下文是当前词和它前面n-1个标识符的词性标记，如图5.1所示。要选择的标记是圆圈里的tn，灰色阴影的是上下文。在5.1所示的n-gram标注器的例子中，我们让n=3；也就是说，我们考虑当前词的前两个词的标记。一个n-gram标注器挑选在给定的上下文中最有可能的标记。\n",
    "\n",
    "![5.1.png](./picture/5.1.png)\n",
    "NgramTagger类使用一个已标注的训练语料库来确定对每个上下文哪个词性标记最有可能。这里我们看n-gram标注器的一个特殊情况，二元标注器。首先，我们训练它，然后用它来标注未标注的句子："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 114,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[('Various', 'JJ'), ('of', 'IN'), ('the', 'AT'), ('apartments', 'NNS'), ('are', 'BER'), ('of', 'IN'), ('the', 'AT'), ('terrace', 'NN'), ('type', 'NN'), (',', ','), ('being', 'BEG'), ('on', 'IN'), ('the', 'AT'), ('ground', 'NN'), ('floor', 'NN'), ('so', 'CS'), ('that', 'CS'), ('entrance', 'NN'), ('is', 'BEZ'), ('direct', 'JJ'), ('.', '.')]\n"
     ]
    }
   ],
   "source": [
    "bigram_tagger = nltk.BigramTagger(train_sents)\n",
    "print(bigram_tagger.tag(brown_sents[2007]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 115,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[('The', 'AT'), ('population', 'NN'), ('of', 'IN'), ('the', 'AT'), ('Congo', 'NP'), ('is', 'BEZ'), ('13.5', None), ('million', None), (',', None), ('divided', None), ('into', None), ('at', None), ('least', None), ('seven', None), ('major', None), ('``', None), ('culture', None), ('clusters', None), (\"''\", None), ('and', None), ('innumerable', None), ('tribes', None), ('speaking', None), ('400', None), ('separate', None), ('dialects', None), ('.', None)]\n"
     ]
    }
   ],
   "source": [
    "unseen_sent = brown_sents[4203]\n",
    "print(bigram_tagger.tag(unseen_sent))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "请注意，二元标注器能够标注训练中它看到过的句子中的所有词，但对一个没见过的句子表现很差。只要遇到一个新词（如13.5），就无法给它分配标记。它不能标注下面的词（如million)，即使是在训练过程中看到过的，只是因为在训练过程中从来没有见过它前面有一个None标记的词。因此，标注器标注句子的其余部分也失败了。它的整体准确度得分非常低："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 116,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.10206319146815508\n"
     ]
    }
   ],
   "source": [
    "print(bigram_tagger.evaluate(test_sents))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "当n越大，上下文的特异性就会增加，我们要标注的数据中包含训练数据中不存在的上下文的几率也增大。这被称为数据稀疏问题，在NLP中是相当普遍的。因此，我们的研究结果的精度和覆盖范围之间需要有一个权衡（这与信息检索中的精度/召回权衡有关）。\n",
    "\n",
    "小心！\n",
    "\n",
    "N-gram标注器不应考虑跨越句子边界的上下文。因此，NLTK的标注器被设计用于句子列表，其中一个句子是一个词列表。在一个句子的开始，tn-1和前面的标记被设置为None。\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 5.4 组合标注器\n",
    "\n",
    "解决精度和覆盖范围之间的权衡的一个办法是尽可能的使用更精确的算法，但却在很多时候落后于具有更广覆盖范围的算法。例如，我们可以按如下方式组合二元标注器、一元注器和一个默认标注器，如下：\n",
    "\n",
    "    1.尝试使用二元标注器标注标识符。\n",
    "    2.如果二元标注器无法找到一个标记，尝试一元标注器。\n",
    "    3.如果一元标注器也无法找到一个标记，使用默认标注器。\n",
    "\n",
    "大多数NLTK标注器允许指定一个回退标注器。回退标注器自身可能也有一个回退标注器："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 117,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.8452108043456593\n"
     ]
    }
   ],
   "source": [
    "t0 = nltk.DefaultTagger(\"NN\")\n",
    "t1 = nltk.UnigramTagger(train_sents, backoff = t0)\n",
    "t2 = nltk.BigramTagger(train_sents, backoff = t1)\n",
    "print(t2.evaluate(test_sents))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 5.5 标注生词\n",
    "\n",
    "我们标注生词的方法仍然是回退到一个正则表达式标注器或一个默认标注器。这些都无法利用上下文。因此，如果我们的标注器遇到词blog，训练过程中没有看到过，它会分配相同的标记，不论这个词出现的上下文是the blog还是to blog。我们怎样才能更好地处理这些生词，或词汇表以外的项目？\n",
    "\n",
    "一个有用的基于上下文标注生词的方法是限制一个标注器的词汇表为最频繁的n 个词，使用3中的方法替代每个其他的词为一个特殊的词UNK。训练时，一个一元标注器可能会学到UNK通常是一个名词。然而，n-gram标注器会检测它的一些其他标记中的上下文。例如，如果前面的词是to（标注为TO），那么UNK可能会被标注为一个动词。\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 5.6 存储标注器\n",
    "\n",
    "在大语料库上训练一个标注器可能需要大量的时间。没有必要在每次我们需要的时候训练一个标注器，很容易将一个训练好的标注器保存到一个文件以后重复使用。让我们保存我们的标注器t2到文件t2.pkl。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 122,
   "metadata": {},
   "outputs": [],
   "source": [
    "from pickle import dump\n",
    "output = open('5.t2.pkl', 'wb')\n",
    "dump(t2, output, -1)\n",
    "output.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "现在，我们可以在一个单独的Python进程中，我们可以载入保存的标注器。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 123,
   "metadata": {},
   "outputs": [],
   "source": [
    "from pickle import load\n",
    "input = open(\"5.t2.pkl\", \"rb\")\n",
    "tagger = load(input)\n",
    "input.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "现在让我们检查它是否可以用来标注."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 124,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[('The', 'AT'), (\"board's\", 'NN$'), ('action', 'NN'), ('shows', 'NNS'), ('what', 'WDT'), ('free', 'JJ'), ('enterprise', 'NN'), ('is', 'BEZ'), ('up', 'RP'), ('against', 'IN'), ('in', 'IN'), ('our', 'PP$'), ('complex', 'JJ'), ('maze', 'NN'), ('of', 'IN'), ('regulatory', 'NN'), ('laws', 'NNS'), ('.', '.')]\n"
     ]
    }
   ],
   "source": [
    "text = \"\"\"The board's action shows what free enterprise\n",
    "...     is up against in our complex maze of regulatory laws .\"\"\"\n",
    "tokens = text.split()\n",
    "print(tagger.tag(tokens))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 5.7 准确性的极限\n",
    "\n",
    "一个n-gram标注器准确性的上限是什么？考虑一个三元标注器的情况。它遇到多少词性歧义的情况？我们可以根据经验决定这个问题的答案："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 130,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.049297702068029296\n"
     ]
    }
   ],
   "source": [
    ">>> cfd = nltk.ConditionalFreqDist(\n",
    "...            ((x[1], y[1], z[0]), z[1])\n",
    "...            for sent in brown_tagged_sents\n",
    "...            for x, y, z in nltk.trigrams(sent))\n",
    "\n",
    "ambiguous_contexts = [c for c in cfd.conditions() if len(cfd[c]) > 1]\n",
    "print(sum(cfd[c].N() for c in ambiguous_contexts) / cfd.N())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "因此，1/20的三元是有歧义的[示例]。给定当前单词及其前两个标记，根据训练数据，在5％的情况中，有一个以上的标记可能合理地分配给当前词。假设我们总是挑选在这种含糊不清的上下文中最有可能的标记，可以得出三元标注器准确性的一个下界。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "调查标注器准确性的另一种方法是研究它的错误。有些标记可能会比别的更难分配，可能需要专门对这些数据进行预处理或后处理。一个方便的方式查看标注错误是混淆矩阵。它用图表表示期望的标记（黄金标准）与实际由标注器产生的标记："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 133,
   "metadata": {},
   "outputs": [],
   "source": [
    "test_tags = [tag for sent in brown.sents(categories  = \"editorial\") for (word, tag) in t2.tag(sent)]\n",
    "gold_tags = [tag for (word, tag) in brown.tagged_words(categories='editorial')]\n",
    "#print(nltk.ConfusionMatrix(gold_tags, test_tags))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "基于这样的分析，我们可能会决定修改标记集。或许标记之间很难做出的区分可以被丢弃，因为它在一些较大的处理任务的上下文中并不重要。\n",
    "\n",
    "分析标注器准确性界限的另一种方式来自人类标注者之间并非100％的意见一致。[更多]\n",
    "\n",
    "一般情况下，标注过程会损坏区别：例如当所有的人称代词被标注为PRP时，词的特性通常会失去。与此同时，标注过程引入了新的区别从而去除了含糊之处：例如deal标注为VB或NN。这种消除某些区别并引入新的区别的特点是标注的一个重要的特征，有利于分类和预测。当我们引入一个标记集的更细的划分时，在n-gram标注器决定什么样的标记分配给一个特定的词时，可以获得关于左侧上下文的更详细的信息。然而，标注器同时也将需要做更多的工作来划分当前的词符，只是因为有更多可供选择的标记。相反，使用较少的区别（如简化的标记集），标注器有关上下文的信息会减少，为当前词符分类的选择范围也较小。\n",
    "\n",
    "我们已经看到，训练数据中的歧义导致标注器准确性的上限。有时更多的上下文能解决这些歧义。然而，在其他情况下，如(Church, Young, & Bloothooft, 1996)中指出的，只有参考语法或现实世界的知识，才能解决歧义。尽管有这些缺陷，词性标注在用统计方法进行自然语言处理的兴起过程中起到了核心作用。1990年代初，统计标注器令人惊讶的精度是一个惊人的示范，可以不用更深的语言学知识解决一小部分语言理解问题，即词性消歧。这个想法能再推进吗？第7.中，我们将看到，它可以。\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 6 基于转换的标注\n",
    "\n",
    "n-gram标注器的一个潜在的问题是它们的n-gram表（或语言模型）的大小。如果使用各种语言技术的标注器部署在移动计算设备上，在模型大小和标注器准确性之间取得平衡是很重要的。使用回退标注器的n-gram标注器可能存储trigram和bigram表，这是很大的稀疏阵列，可能有数亿条条目。\n",
    "\n",
    "第二个问题是关于上下文。n-gram标注器从前面的上下文中获得的唯一的信息是标记，虽然词本身可能是一个有用的信息源。n-gram模型使用上下文中的词的其他特征为条件是不切实际的。在本节中，我们考察Brill标注，一种归纳标注方法，它的性能很好，使用的模型只有n-gram标注器的很小一部分。\n",
    "\n",
    "Brill标注是一种基于转换的学习，以它的发明者命名。一般的想法很简单：猜每个词的标记，然后返回和修复错误。在这种方式中，Brill标注器陆续将一个不良标注的文本转换成一个更好的。与n-gram标注一样，这是有监督的学习方法，因为我们需要已标注的训练数据来评估标注器的猜测是否是一个错误。然而，不像n-gram标注，它不计数观察结果，只编制一个转换修正规则列表。\n",
    "\n",
    "Brill标注的的过程通常是与绘画类比来解释的。假设我们要画一棵树，包括大树枝、树枝、小枝、叶子和一个统一的天蓝色背景的所有细节。不是先画树然后尝试在空白处画蓝色，而是简单的将整个画布画成蓝色，然后通过在蓝色背景上上色“修正”树的部分。以同样的方式，我们可能会画一个统一的褐色的树干再回过头来用更精细的刷子画进一步的细节。Brill标注使用了同样的想法：以大笔画开始，然后修复细节，一点点的细致的改变。让我们看看下面的例子："
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```py\n",
    ">>> nltk.tag.brill.demo()\n",
    "Training Brill tagger on 80 sentences...\n",
    "Finding initial useful rules...\n",
    "    Found 6555 useful rules.\n",
    "\n",
    "           B      |\n",
    "   S   F   r   O  |        Score = Fixed - Broken\n",
    "   c   i   o   t  |  R     Fixed = num tags changed incorrect -> correct\n",
    "   o   x   k   h  |  u     Broken = num tags changed correct -> incorrect\n",
    "   r   e   e   e  |  l     Other = num tags changed incorrect -> incorrect\n",
    "   e   d   n   r  |  e\n",
    "------------------+-------------------------------------------------------\n",
    "  12  13   1   4  | NN -> VB if the tag of the preceding word is 'TO'\n",
    "   8   9   1  23  | NN -> VBD if the tag of the following word is 'DT'\n",
    "   8   8   0   9  | NN -> VBD if the tag of the preceding word is 'NNS'\n",
    "   6   9   3  16  | NN -> NNP if the tag of words i-2...i-1 is '-NONE-'\n",
    "   5   8   3   6  | NN -> NNP if the tag of the following word is 'NNP'\n",
    "   5   6   1   0  | NN -> NNP if the text of words i-2...i-1 is 'like'\n",
    "   5   5   0   3  | NN -> VBN if the text of the following word is '*-1'\n",
    "   ...\n",
    ">>> print(open(\"errors.out\").read())\n",
    "             left context |    word/test->gold     | right context\n",
    "--------------------------+------------------------+--------------------------\n",
    "                          |      Then/NN->RB       | ,/, in/IN the/DT guests/N\n",
    ", in/IN the/DT guests/NNS |       '/VBD->POS       | honor/NN ,/, the/DT speed\n",
    "'/POS honor/NN ,/, the/DT |    speedway/JJ->NN     | hauled/VBD out/RP four/CD\n",
    "NN ,/, the/DT speedway/NN |     hauled/NN->VBD     | out/RP four/CD drivers/NN\n",
    "DT speedway/NN hauled/VBD |      out/NNP->RP       | four/CD drivers/NNS ,/, c\n",
    "dway/NN hauled/VBD out/RP |      four/NNP->CD      | drivers/NNS ,/, crews/NNS\n",
    "hauled/VBD out/RP four/CD |    drivers/NNP->NNS    | ,/, crews/NNS and/CC even\n",
    "P four/CD drivers/NNS ,/, |     crews/NN->NNS      | and/CC even/RB the/DT off\n",
    "NNS and/CC even/RB the/DT |    official/NNP->JJ    | Indianapolis/NNP 500/CD a\n",
    "                          |     After/VBD->IN      | the/DT race/NN ,/, Fortun\n",
    "ter/IN the/DT race/NN ,/, |    Fortune/IN->NNP     | 500/CD executives/NNS dro\n",
    "s/NNS drooled/VBD like/IN |  schoolboys/NNP->NNS   | over/IN the/DT cars/NNS a\n",
    "olboys/NNS over/IN the/DT |      cars/NN->NNS      | and/CC drivers/NNS ./.\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 7 如何确定一个词的分类\n",
    "\n",
    "我们已经详细研究了词类，现在转向一个更基本的问题：我们如何首先决定一个词属于哪一类？在一般情况下，语言学家使用形态学、句法和语义线索确定一个词的类别。\n",
    "## 7.1 形态学线索\n",
    "\n",
    "一个词的内部结构可能为这个词分类提供有用的线索。举例来说：-ness是一个后缀，与形容词结合产生一个名词，如happy → happiness, ill → illness。如果我们遇到的一个以-ness结尾的词，很可能是一个名词。同样的，-ment是与一些动词结合产生一个名词的后缀，如govern → government和establish → establishment。\n",
    "\n",
    "英语动词也可以是形态复杂的。例如，一个动词的现在分词以-ing结尾，表示正在进行的还没有结束的行动（如falling, eating）。-ing后缀也出现在从动词派生的名词中，如the falling of the leaves（这被称为动名词）。\n",
    "## 7.2 句法线索\n",
    "\n",
    "另一个信息来源是一个词可能出现的典型的上下文语境。例如，假设我们已经确定了名词类。那么我们可以说，英语形容词的句法标准是它可以立即出现在一个名词前，或紧跟在词be或very后。根据这些测试，near应该被归类为形容词：\n",
    "```\n",
    "Statement  User117 Dude..., I wanted some of that\n",
    "ynQuestion User120 m I missing something?\n",
    "Bye        User117 I'm gonna go fix food, I'll be back later.\n",
    "System     User122 JOIN\n",
    "System     User2   slaps User122 around a bit with a large trout.\n",
    "Statement  User121 18/m pm me if u tryin to chat\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
